﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC.Read.Api.MYSQL;

namespace RBAC.Read.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DatabaseBackupController : ControllerBase
    {
        private readonly IDatabaseBackupService _backupService;
        private readonly string _backupDirectory;

        public DatabaseBackupController(IDatabaseBackupService backupService, IConfiguration configuration)
        {
            _backupService = backupService;
            _backupDirectory = configuration["BackupDirectory"] ?? Path.Combine(Directory.GetCurrentDirectory(), "Backups");

            if (!Directory.Exists(_backupDirectory))
            {
                Directory.CreateDirectory(_backupDirectory);
            }
        }

        [HttpPost("backup")]
        public async Task<IActionResult> BackupDatabase()
        {
            var fileName = $"backup_{DateTime.Now:yyyyMMdd_HHmmss}.sql";
            var fullPath = Path.Combine(_backupDirectory, fileName);

            var success = await _backupService.BackupDatabaseAsync(fullPath);

            if (success)
            {
                return Ok(new { Message = "备份成功", FilePath = fullPath });
            }

            return StatusCode(500, new { Message = "备份失败" });
        }

        [HttpPost("restore")]
        public async Task<IActionResult> RestoreDatabase([FromBody] RestoreRequest request)
        {
            if (string.IsNullOrEmpty(request.BackupPath))
            {
                return BadRequest(new { Message = "备份路径不能为空" });
            }

            var success = await _backupService.RestoreDatabaseAsync(request.BackupPath);

            if (success)
            {
                return Ok(new { Message = "恢复成功" });
            }

            return StatusCode(500, new { Message = "恢复失败" });
        }

        [HttpGet("list")]
        public async Task<IActionResult> ListBackups()
        {
            var backups = await _backupService.ListBackupsAsync(_backupDirectory);
            return Ok(backups);
        }
    }
    public class RestoreRequest
    {
        public string BackupPath { get; set; }
    }
}
